package utils;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;

import dbhelper.Users;

import entities.User;
public class UsersHelper {
public final static int MINPASSWORDSIZE = 5;
private static final int SALTSIZE = 10;

	/*
	 * checks if the user name and the password are ok 

	 */
	private static boolean checkPassword(User user,User DBUser){
		if(user.getUserName() == null || user.getUserName().isEmpty())
		return false;
		return (DBUser != null) && 
		(enc(user.getPassword(),DBUser.getSalt()).equals(DBUser.getSaltedPasswod()))
				 ? true : false;		
	}
	
	private static String enc(String toEncrypt,String salt) {

		return DigestUtils.md5Hex(toEncrypt + salt);

	}
	/**
	 * registers a new user 
	 * @param user
	 */
	public static boolean registerNewUser(User user){
		if(user != null && validPassword(user.getPassword()) && validUserName(user.getUserName())){
			user.setSalt(RandomStringUtils.randomAlphanumeric(SALTSIZE));
			user.setSaltedPasswod(enc(user.getPassword(),user.getSalt()));
			if(!StringUtils.isNotBlank(
					user.getDisplayName()))
				user.setDisplayName(user.getUserName());
			return (!Users.checkIfUserNameExists(user)) ? Users.register(user) : false;
		}
		return false;
	}
	
	private static boolean validPassword(String password){
		
		return password != null && !password.isEmpty() && password.length() > MINPASSWORDSIZE
				&& letterDigitConstrains(password);
				
	}
	
	//checks if the string has at least one number and one letter
	private static boolean letterDigitConstrains(String string){
		boolean digit = false,letter = false;
		for(int i=0;i<string.length();i++){
			if(Character.isLetter(string.charAt(i)))
				letter=true;
			if(Character.isDigit(string.charAt(i)))
				digit=true;
			if(digit && letter)
				return true;
		}
		return false;
	}
	
	private static boolean validUserName(String userName){
		return userName != null && !userName.isEmpty();
	}
	
	/**
	 * login the user 
	 * @param user
	 * @return the user entity from DB 
	 * if its not successful return null
	 */
	public static User login(User user){
		if(user != null && validUserName(user.getUserName()) && validPassword(user.getPassword())){
			User DBUser =  Users.getUser(user);
			if(checkPassword(user, DBUser))
				return DBUser;
		}
		return null;
	}
}
